//
//  F_FoodMatch_VC.swift
//  MyFood
//
//  Created by dllo on 16/2/19.
//  Copyright © 2016年 XRG. All rights reserved.
//

import UIKit
import SwiftyJSON
class F_FoodMatch_VC: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {

    var collectionView : UICollectionView!
    var materialBigArr = Array<F_Material_Collection_Model>()
    var collectionArr = Array<F_Material_Second_Collection_Model>()
    var littleView : UIView!
    var littleTableView: UITableView!
    var isSelected : Bool!
    var button : UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        button = UIButton(type: UIButtonType.Custom)
        button.frame = CGRectMake(0, 0, 30, 30)
        button.setImage(UIImage(named: "113"), forState: UIControlState.Normal)
        button.addTarget(self, action: "clickAllAction", forControlEvents: UIControlEvents.TouchUpInside)

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

        self.isSelected = false
        createCollection()
        createLittleTable()
        createData()
        self.title = "食材搭配"
        // Do any additional setup after loading the view.
    }

    func clickAllAction(){

        self.isSelected = !self.isSelected
        if self.isSelected == true {

            button.setImage(UIImage(named: "11"), forState: UIControlState.Normal)

            UIView.animateWithDuration(1, animations: { () -> Void in
           self.littleView.frame = CGRectMake(BASE_WIDTH / 2, 0, BASE_WIDTH/2, BASE_HEIGHT)
            })

        }else{
            button.setImage(UIImage(named: "113"), forState: UIControlState.Normal)
            UIView.animateWithDuration(1, animations: { () -> Void in
                self.littleView.frame = CGRectMake(BASE_WIDTH, 0, BASE_WIDTH/2, BASE_HEIGHT)
            })
        }

    }



    func createCollection(){

        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSizeMake((BASE_WIDTH - 50)/4, (BASE_WIDTH - 50)/3)
        self.collectionView = UICollectionView(frame: CGRectMake(10, 0, BASE_WIDTH - 20, BASE_HEIGHT), collectionViewLayout: flowLayout)
        self.view.addSubview(self.collectionView)
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.minimumLineSpacing = 10

        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.showsVerticalScrollIndicator = false
        collectionView.pagingEnabled = true
        collectionView.bounces = false
        self.collectionView.delegate = self
        self.collectionView.dataSource = self

    self.collectionView.registerNib(UINib(nibName: "R_FoodMatch_CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func createLittleTable(){

        self.littleView = UIView(frame: CGRectMake(BASE_WIDTH, 0, BASE_WIDTH / 2, BASE_HEIGHT))
        self.littleTableView = UITableView(frame: self.littleView.bounds, style: UITableViewStyle.Plain)
        self.littleView.addSubview(self.littleTableView)
        self.littleTableView.delegate = self
        self.littleTableView.dataSource = self
        self.littleTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tabCell")

        self.view.addSubview(self.littleView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.materialBigArr.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("tabCell")
        let bigModel = self.materialBigArr[indexPath.row]
        cell?.textLabel?.text = bigModel.text
        cell!.textLabel!.highlightedTextColor = UIColor.orangeColor()
       let view = UIView();
        view.backgroundColor = UIColor.clearColor();
        cell!.selectedBackgroundView = view;
        return cell!
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {


        let model = self.materialBigArr[indexPath.row]
        self.collectionArr = model.data
        self.collectionView.reloadData()
        clickAllAction()

    }

    func createData(){

        XRAFNetworkTool.POSTUrl(BASE_URL, body: "methodName=MaterialSubtype&version=4.3.1&", requestBodyStyle: XRRequestStyle.String, headFile: nil, response: XRResponseStyle.XRJSON, success: { (task, result) -> Void in

            let json = JSON(result)
            let arr = json["data"]["data"].array

            self.materialBigArr = Array()

            for temp in arr!{

                let dic : Dictionary = temp.dictionaryObject!
                let model = F_Material_Collection_Model(dic:dic)

                let smallarr = temp["data"].array
                model.data = Array()
                self.collectionArr = Array()
                for temp1 in smallarr!{
                    let dic : Dictionary = temp1.dictionaryObject!
                    let model1 = F_Material_Second_Collection_Model(dic:dic)
                    model.data.append(model1)

                }
                self.materialBigArr.append(model)
            }

            if self.materialBigArr.count != 0 {
                self.littleTableView.reloadData()
                // #pragma 设置默认选择在第一行
                let first = NSIndexPath(forItem: 0, inSection: 0)
                self.littleTableView.selectRowAtIndexPath(first, animated: true, scrollPosition: UITableViewScrollPosition.Top)
                // 先把第一个取出来.
                let bigModel = self.materialBigArr[0]
                self.collectionArr = bigModel.data
                if self.collectionArr.count != 0 {
                    self.collectionView.reloadData()
                }
            }
            }) { (task, error) -> Void in
                print(error)
        }
    }


    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return self.collectionArr.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell : R_FoodMatch_CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! R_FoodMatch_CollectionViewCell
        let model = self.collectionArr[indexPath.row]
        cell.foodImg.sd_setImageWithURL(NSURL(string: model.image), placeholderImage: UIImage(named: "空白1"))
        cell.foodName.text = model.text
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        let cell = collectionView.cellForItemAtIndexPath(indexPath)
        let model = self.collectionArr[indexPath.row]
        print("选择了\(model.text)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
